package cn.rongdao.jrkabao.ui.main

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.mifengkong.appcommon.buriedpoint.YingyongbaoAppidAndKeyList
import cn.mifengkong.appcommon.buriedpoint.YingyongbaoBuriedUtil
import cn.rongdao.jrkabao.R
import cn.rongdao.jrkabao.base.BaseActivity
import cn.rongdao.jrkabao.base.FRBaseNeedLocationActivity
import cn.rongdao.jrkabao.constant.InfoConstant
import cn.rongdao.jrkabao.constant.SPConstant
import cn.rongdao.jrkabao.ui.main.mainfragment.FragmentFinancing
import cn.rongdao.jrkabao.ui.main.mainfragment.FragmentLoan
import cn.rongdao.jrkabao.ui.main.mainfragment.FragmentOtherLoan
import cn.rongdao.jrkabao.ui.main.mainfragment.FragmentRemind
import cn.rongdao.jrkabao.ui.main.mainfragment.cashadvance.FragmentCashAdvance
import cn.rongdao.jrkabao.ui.main.mainfragment.personal.FragmentPersonal
import cn.rongdao.jrkabao.ui.main.tab.TabUIComponent
import cn.rongdao.jrkabao.util.growingio.BuriedUtil
import cn.rongdao.jrkabao.util.growingio.YingYongBaoBuriedHelper
import com.baidu.location.BDLocation
import com.mifengkong.frtools.ui.activity.FRStartActivity
import com.mifengkong.frtools.util.FRSharedPreferences
import com.mifengkong.frtools.util.FRToast
import com.mifengkong.kotlincommon.indicator.IndicatorAdapter
import com.mifengkong.kotlincommon.indicator.TrackIndicatorView
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.reflect.Field
import java.util.*
import kotlin.collections.ArrayList

/**
 * Created by jack on 2018/6/1
 */
open class MainActivity : FRBaseNeedLocationActivity() {

    companion object {
        const val IS_GE_TUI = "is_ge_tui"
        fun start(context: Context) {
            FRStartActivity.start(context, MainActivity::class.java)
        }

        fun start(context: Context, isGeTui: Boolean) {
            val bundle = Bundle()
            bundle.putBoolean(IS_GE_TUI, isGeTui)
            FRStartActivity.start(context, MainActivity::class.java, bundle, Intent.FLAG_ACTIVITY_NEW_TASK)
        }

        fun start(context: Context, fragmentTag: String) {
            val bundle = Bundle()
            bundle.putString("fragment_tag", fragmentTag)
            FRStartActivity.start(context, MainActivity::class.java, bundle)
        }
    }

    private var isSendLocation: Boolean = false
    private var mFragmentTag: String? = null
    private var mFragmentList = ArrayList<Fragment>()
    private var mDrawableList = ArrayList<Int>()
    private lateinit var mTabNameList: List<String>
    private var tabDrawableMap = HashMap<String, Int>()
    private var fragmentMap = HashMap<String, Fragment>()
    private lateinit var fragmentOtherLoan: FragmentOtherLoan

    private var mFlag = false
    private var mTimeout: Long = -1

    override fun layoutRes(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        super.initView()
        startLocate()
        initFragmentAndDrawable()

        initViewPager()
        buriedActivatePoint4YingYongBao()
    }

    private fun initFragmentAndDrawable() {
        val fragmentRemind = FragmentRemind()
        val fragmentFinancing = FragmentFinancing()
        val fragmentLoan = FragmentLoan()
        fragmentOtherLoan = FragmentOtherLoan()
        val fragmentPersonal = FragmentPersonal()
        val fragmentCashAdvance = FragmentCashAdvance()
        initFragmentView("CashAdvanceViewController", fragmentCashAdvance, R.drawable.tab_cashadvance_selector)
        initFragmentView("RemindViewController", fragmentRemind, R.drawable.tab_card_manager_selector)
        initFragmentView("FianceViewController", fragmentFinancing, R.drawable.tab_financing_selector)
        initFragmentView("HomeViewController", fragmentLoan, R.drawable.tab_loan_selector)
        initFragmentView("JiebaViewController", fragmentOtherLoan, R.drawable.tab_loan_market_selector)
        initFragmentView("ProfileViewController", fragmentPersonal, R.drawable.tab_personal_selector)

        initFragmentAndDrawableOrder()
    }

    private fun initFragmentAndDrawableOrder() {
        val tabKey = FRSharedPreferences.getString(SPConstant.TAB, SPConstant.TAB_KEY, "")
        val tabName = FRSharedPreferences.getString(SPConstant.TAB, SPConstant.TAB_NAME, "")
        val tabKeyList: List<String> = tabKey.split(",")
        mTabNameList = tabName.split(",")
        for (i in 0 until tabKeyList.size) {
            if (fragmentMap.containsKey(tabKeyList[i])) {
                fragmentMap[tabKeyList[i]]?.let { mFragmentList.add(it) }
                tabDrawableMap[tabKeyList[i]]?.let { mDrawableList.add(it) }
            }
        }
    }

    private fun initFragmentView(str: String, fragment: Fragment, drawableSrc: Int) {
        fragmentMap[str] = fragment
        tabDrawableMap[str] = drawableSrc
    }

    private fun initViewPager() {
        amViewPager.offscreenPageLimit = -1

        amViewPager.adapter = object : FragmentPagerAdapter(supportFragmentManager) {
            override fun getItem(position: Int): Fragment {
                return mFragmentList[position]
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {

            }

            override fun getCount(): Int {
                return mFragmentList.size
            }
        }

        amTrackIndicatorView.setTabVisibleNum(mFragmentList.size)

        amTrackIndicatorView.setAdapter(object : IndicatorAdapter() {
            override fun getItemCount(): Int {
                return mFragmentList.size
            }

            override fun getView(position: Int, parent: ViewGroup): View {
                val tabUIComponent: TabUIComponent = LayoutInflater.from(this@MainActivity).inflate(R.layout.layout_main_tab, parent, false) as TabUIComponent
                tabUIComponent.setImageView(mDrawableList[position])
                tabUIComponent.setTabContent(mTabNameList[position])
                return tabUIComponent
            }

            override fun highLightIndicator(view: View) {
                val tabUIComponent: TabUIComponent = view as TabUIComponent
                tabUIComponent.setTabSelected(true)
            }

            override fun resetIndicator(view: View) {
                val tabUIComponent: TabUIComponent = view as TabUIComponent
                tabUIComponent.setTabSelected(false)
            }

        }, amViewPager)

        amTrackIndicatorView.setOnPageChangeListener(object : TrackIndicatorView.OnPageChangeListener {
            override fun selected(position: Int) {
                if (mTabNameList.isNotEmpty()) {
                    BuriedUtil.kamao_tab_click_apply(thisActivity(), mTabNameList[position])
                    if (isCashAdvanceFragment(position)) {
                        BuriedUtil.kamao_yemian_jiazaiwancheng_apply(thisActivity(), 0)
                    }
                }
            }
        })
    }

    /**
     * 为应用包推广埋激活点
     */
    private fun buriedActivatePoint4YingYongBao() {
        val yingYongBaoBuriedHelper = YingYongBaoBuriedHelper()
        if (YingyongbaoAppidAndKeyList.needRequestQQBycurrentChannelId(yingYongBaoBuriedHelper.applicationId))
            YingyongbaoBuriedUtil.getInstance(yingYongBaoBuriedHelper).activate()
    }

    override fun useEventBus(): Boolean {
        return true
    }

    /**
     * 判断是不是返回操作
     *
     * @return
     */
    private fun checkBackAction(): Boolean {
        val flag = mFlag
        mFlag = true
        val time = 2000L
        val timeout = mTimeout == (-1).toLong() || System.currentTimeMillis() - mTimeout > time
        if (mFlag && (mFlag != flag || timeout)) {
            mTimeout = System.currentTimeMillis()
            //这里写给用户的提示，比如“再点击一次退出应用”
            FRToast.showToastSafe("再点击一次退出应用")
            return true
        }
        return !mFlag
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (mFragmentList[amViewPager.currentItem] is FragmentOtherLoan) {
            if (fragmentOtherLoan.onKeyDown(keyCode)) {
                return true
            } else if (checkBackAction()) {
                return true
            }
        } else if (checkBackAction()) {
            return true
        }
        finish()
        return super.onKeyDown(keyCode, event)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (!fragmentOtherLoan.isHidden) {
            fragmentOtherLoan.onTabActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val isGeTui = intent?.getBooleanExtra(IS_GE_TUI, false) ?: false
        if (isGeTui) {
            if (getRemindIndex() != -1) {
                setCurrentItem(getRemindIndex())
            }
        }
        setIntent(intent)
        mFragmentTag = getIntent().getStringExtra("fragment_tag")
        when (mFragmentTag) {
            InfoConstant.FRAGMENT_TAG_PERSONAL -> showFragmentPersonal()
            InfoConstant.FRAGMENT_TAG_LOAN -> showFragmentLoan()
            InfoConstant.FRAGMENT_TAG_CASHADVANCE -> {
                showFragmentCashAdvance()
                (mFragmentList[amViewPager.currentItem].activity as BaseActivity).sendTaskCoupon()
            }
        }
    }

    fun getFinancingIndex(): Int {
        for (i in mFragmentList.indices) {
            if (mFragmentList[i] is FragmentFinancing) {
                return i
            }
        }
        return -1
    }

    private fun isCashAdvanceFragment(index: Int): Boolean {
        return mFragmentList[index] is FragmentCashAdvance
    }

    private fun getRemindIndex(): Int {
        for (i in mFragmentList.indices) {
            if (mFragmentList[i] is FragmentRemind) {
                return i
            }
        }
        return -1
    }

    private fun getPersonalIndex(): Int {
        for (i in mFragmentList.indices) {
            if (mFragmentList[i] is FragmentPersonal) {
                return i
            }
        }
        return -1
    }

    private fun setCurrentItem(position: Int) {
        try {
            val field: Field = amViewPager.javaClass.getField("mCurItem")
            field.isAccessible = true
            field.setInt(amViewPager, position)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        amViewPager.adapter?.notifyDataSetChanged()
        amViewPager.setCurrentItem(position, false)
    }

    /**
     * 展示个人中心
     */
    private fun showFragmentPersonal() {
        for (i in mFragmentList.indices) {
            if (mFragmentList[i] is FragmentPersonal) {
                setCurrentItem(i)
                break
            }
        }
    }

    /**
     * 展示贷款页面
     */
    private fun showFragmentLoan() {
        for (i in mFragmentList.indices) {
            if (mFragmentList[i] is FragmentLoan) {
                setCurrentItem(i)
                break
            }
        }
    }

    /**
     * 展示个人中心
     */
    private fun showFragmentCashAdvance() {
        for (i in mFragmentList.indices) {
            if (mFragmentList[i] is FragmentCashAdvance) {
                setCurrentItem(i)
                break
            }
        }
    }

    override fun onReceiveLocation(bdLocation: BDLocation?) {
        if (!isSendLocation) {
            mLatitude = bdLocation?.latitude ?: 0.0
            mLongitude = bdLocation?.longitude ?: 0.0
            sendLocation("")
            stopLocate()
            isSendLocation = true
        }
    }

}